/*
 * ConsoleWorkItem.c
 *
 *  Created on: Mar 12, 2012
 *      Author: mikaelgra
 */

#include <stdlib.h>
#include <string.h>

#include "ConsoleWorkItem.h"

/**
 * This creates a new ConsoleWorkItem and places it on
 * the heap.
 *
 * @param displayText
 * 		This is the text displayed in the console when
 * 		this ConsoleWorkItem is processed.
 */
struct stConsoleWorkItem_t* ConsoleWorkItem_New(
		char *displayText,
		bool_t requireInput,
		unsigned char type)
{
	struct stConsoleWorkItem_t *item = (struct stConsoleWorkItem_t*)malloc(sizeof(struct stConsoleWorkItem_t));
	item->requireInput = TRUE;
	item->type = type;

	int length = strlen(displayText) + 1;
	item->displayText = (char*)malloc(length * sizeof(char));
	int i;
	for(i = 0; i < length; i++)
	{
		*(item->displayText + i) = *(displayText + i);
	}

	return item;
}

/**
 * This frees up any member used by the ConsoleWorkItem.
 *
 * @param item
 * 		This is the ConsoleWorkItem to be freed.
 * @param requireInput
 * 		This a boolean indicating whether or not this
 * 		ConsoleWorkItem requires input.
 * @param type
 * 		This is a identifier which identifies the type
 * 		of input this ConsoleWorkItem requires.
 */
void ConsoleWorkItem_Finalize(struct stConsoleWorkItem_t* item)
{
	if(item->displayText != NULL)
	{
		free(item->displayText);
	}
	if(item->result != NULL)
	{
		free(item->result);
	}
	free(item);
}

/**
 * Sets the result parameter of the ConsoleWorkItem
 * using the stack.
 *
 * @param item
 * 		This is the ConsoleWorkItem that the result
 * 		should be set on.
 * @param result
 * 		This is the string that will be copied onto
 * 		the heap and copied into the result.
 */
void ConsoleWorkItem_SetResult(struct stConsoleWorkItem_t* item, char* result)
{
	if(item->result != NULL)
	{
		free(item->result);
	}

	int length = strlen(result) + 1;
	item->result = (char*)malloc(length * sizeof(char));
	int i;
	for(i = 0; i < length; i++)
	{
		*(item->result + i) = *(result + i);
	}
}
